package com.kingdee.openimport.patch_service.controller;

import com.kingdee.openimport.patch_service.enume.ErrorCode;
import com.kingdee.openimport.patch_service.exception.PatchException;
import com.kingdee.openimport.patch_service.model.Patch;
import com.kingdee.openimport.patch_service.service.ICheckService;
import com.kingdee.openimport.patch_service.service.IPatchRedisService;
import com.kingdee.openimport.patch_service.service.IPatchService;
import com.kingdee.openimport.patch_service.util.KeyUtil;
import com.kingdee.openimport.patch_service.util.Result;
import com.kingdee.openimport.patch_service.util.ResultUtil;
import com.kingdee.openimport.patch_service.vo.PatchVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Niki on 2018/4/21 14:29
 */
@RestController()
@RequestMapping("/patch")
public class PatchController {
    @Resource
    IPatchService patchService;
    @Resource
    IPatchRedisService patchRedisService;
    @Resource
    ICheckService checkService;

    /**
     * 上传补丁
     *
     * @return
     */
    @PostMapping("/load")
    public Result loadPatch(String version, String type, String className, String description, MultipartFile file) throws PatchException {
        checkService.checkVersion(version);
        checkService.checkType(type);
        checkService.checkFile(file);
        Patch patch = new Patch();
        patch.setVersion(version);
        patch.setType(type);
        patch.setClassName(className);
        patch.setDescription(description);
        patch.setPublishDate(new Date());
        String id = KeyUtil.getUniqueKey();
        patch.setId(id);

        try {
            byte[] patchByte = file.getBytes();
            patchRedisService.putPatch(id, patchByte);
            patchRedisService.setPatchKey(version, id);
        } catch (IOException e) {
            throw ErrorCode.returnException(ErrorCode.SAVE_FILE_ERROR);
        }
        patchService.create(patch);
        return ResultUtil.success();
    }

    @GetMapping(value = "/{version}")
    public Result getPatch(@PathVariable String version) throws PatchException {
        //校验版本的真实性
        checkService.checkVersion(version);
        List<Patch> patchList = patchService.findByVersion(version);
        if (patchList == null || patchList.isEmpty()) {
            throw ErrorCode.returnException(ErrorCode.NO_PATTCH);
        }
        List<PatchVO> vos = patchList.stream().map(e -> PatchVO.patchToVO(e, patchRedisService)).collect(Collectors.toList());
        return ResultUtil.success(vos);
    }
}
